$(function (){
    //初始化数据方法
    initDate();

    //点击确认订单
    $("#tjdd-btn").click(function (){
        $.post(
            "productCarShopping",
            $("#form-order").serialize(),
            function (msg){
                if(msg.code==500){
                    alert("库存不够：请联系商家");
                }else if(msg.data==1){
                    //
                    sessionStorage.removeItem("indexObj");
                    sessionStorage.removeItem("shoppingCar");
                    alert("下单成功，真正为你发速发货！");
                    location.href="my/order.html";
                }else{
                    alert("订单异常");
                }
            },
            "json"
        );
    });
});
//初始化数据
function initDate(){
    //拿到保存的商品
    var shoppingCar = sessionStorage.getItem("shoppingCar");
    //拿到购买的商品
    var indexObj = sessionStorage.getItem("indexObj");
    //转成js
    shoppingCar = JSON.parse(shoppingCar);
    indexObj = JSON.parse(indexObj);
    let index = indexObj.indexStr;
    //定义一个变量装总价
    var sumPrice=0;
    //循环
    for (let i = 0; i < index.length; i++) {
        var product = shoppingCar[index[i]];
        var tr=$(`<tr>
                      <td class="text-muted">
                        <input type="hidden" name="pid" value="${product.id}">
                        ${product.name}
                      </td>
                      <td>${product.price}</td>
                      <td>${product.num}</td>
                      <td>${product.price*product.num}</td>
                    </tr>`);
        sumPrice=sumPrice+(product.price*product.num);
        $("#tbody").append(tr);
    }
    //给总价格赋值
    $("#sumPrice").text(sumPrice);

    //拿到session里面的对象
    var MsgUser = sessionStorage.getItem("user");
    var uid= JSON.parse(MsgUser).id;

    //调用根据用户id查询收货地址
    $.get(
        "AddressQueryByUserid",
        {userid:uid},
        function (msg){
            let addres=msg.data;
            for (let i = 0; i < addres.length; i++) {
                let tr=$(`<label class="d-block">
                                  <input type="radio" name="addr" checked="checked" value="1"/>
                                  <span>${addres[i].contacts} ${addres[i].address}<span class="text-primary">${addres[i].tel}</span>]</span>
                          </label>`);
                //判断默认选中第一个
                if(addres[i].def==1){
                    tr.find("input").prop("checked",true);
                }
                //追加
                $("#user-address").append(tr);
            }
        },
        "json"
    )
}